#include <QPainter>
#include <QDebug>
#include <rviz_common/logging.hpp>
#include "rviz_custom_plugins/widgets/video_widget.h"
#include <controller_msgs/msg/visbot_rect.hpp>

using controller_msgs::msg::VisbotRect;

namespace rviz_custom_plugins {

namespace widgets {

VideoWidget::VideoWidget(QWidget *parent) : QWidget(parent) {
    boxArrPtr = nullptr;
    decoder = new av_codec::VideoDecoder();
    connect(decoder, &VideoDecoder::frameReady, this, &VideoWidget::updateFrame);
    connect(decoder, &VideoDecoder::error,
            [](const QString &err) { qWarning()<< "Error:" << err; });
}

QSize VideoWidget::sizeHint() const
{
    return QSize(320, 240);
}


void VideoWidget::updateFrame(const QImage &frame) {
    QMutexLocker locker(&mutex);
    currentFrame = frame;
    update();
}

void VideoWidget::paintEvent(QPaintEvent * event) {
    QPainter painter(this);
    painter.fillRect(rect(), Qt::black);

    QMutexLocker locker(&mutex);
    if (!currentFrame.isNull()) {
        painter.drawImage(rect(), currentFrame);
    } else {
        painter.setPen(Qt::white);
        painter.drawText(rect(), Qt::AlignCenter, "No video streaming");
    }

    if(boxArrPtr && sizeof(boxArrPtr->object_array) > 0) {
        for (const auto& box : boxArrPtr->object_array) {  // 遍历vector
            int color = box.rect_color;
            VisbotRect rect = box.object_rect;

            // 设置画笔颜色（边框）
            painter.setPen(QColor::fromRgb(color));
            // 设置画刷颜色（填充）
            // painter.setBrush(Qt::red);
            // 绘制矩形(x, y, width, height)

            int w = width();   // 宽度
            int h = height(); // 高度
            painter.drawRect(w * rect.rect_x, h * rect.rect_y, w * rect.rect_width, h * rect.rect_height);

            // std::ostringstream sstm;
            // sstm << "rect.x:" << w * rect.rect_x
            //      << " rect.y:" << h * rect.rect_y
            //      << " rect.width:" << w * rect.rect_width
            //      << " rect.height:" << h * rect.rect_height;
            // RVIZ_COMMON_LOG_WARNING(sstm.str().c_str());
        }
    }
}

void VideoWidget::setVideoUrl(QString url) {
    videoUrl = url;
}

QString VideoWidget::getVideoUrl() {
    return videoUrl;
}

void VideoWidget::start() {
    decoder->startPlay(videoUrl);
}

void VideoWidget::stop() {
    decoder->stop();
}

void VideoWidget::pause() {
    decoder->pause();
}

void VideoWidget::resume() {
    decoder->resume();
}

void VideoWidget::setVisbotIDBoxArr(const VisbotIDBoxArr::ConstSharedPtr& visbotIDBoxArr)
{
    QMutexLocker locker(&mutex);
    boxArrPtr = std::make_shared<VisbotIDBoxArr>(*visbotIDBoxArr);
}

}

}
